import json
import re

from django.contrib.auth import authenticate, login
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.orders.models import OrderInfo
from apps.users.models import User, Userwallet, AdminPay
from utils.view import LoginRequiredJsonMixin


class AdminLogin(View):
    """管理员登录"""

    def post(self, request):
        json_data = request.body.decode()
        json_dict = json.loads(json_data)  # 将JSON字符串，转成python的标准字典
        # 后端校验
        username = json_dict.get("username")
        password = json_dict.get("password")
        if not all([username, password]):
            return JsonResponse({'code': 400, 'error': '参数不全'})

        if re.match('^1[3-9]\d{9}$', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'
        if not re.match(r"^[a-zA-Z0-9_-]{5,20}$", username):
            return JsonResponse({'code': 400, 'error': '请输入正确格式的用户名'})
        if not re.match(r'^[0-9a-zA-Z]{5,20}$', password):
            return JsonResponse({'code': 400, 'error': '密码长度、格式不正确。长度5-20，必须数字字母'})
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({'code': 400, 'error': '账号或者密码错误'})
        if user.is_superuser != 1:
            return JsonResponse({'code': 400, 'error': '账号或者密码错误'})
        # if not remembered:
        #     # 没有记住登陆：状态保持在浏览器会话结束后就销毁
        #     request.session.set_expiry(0)  # 单位秒
        else:
            # 记住登陆：状态保持两周：默认是两周
            request.session.set_expiry(None)
        # except Exception as e:
        #     logger.error(e)
        login(request, user)
        response = JsonResponse({'code': 200, 'error': '登陆成功'})
        u = json.dumps(user.nick_name)  # 用户名序列化
        # print(user.nick_name)
        response.set_cookie("username", u)  # 用户名写入cookie
        return response


class AdminIntegral(LoginRequiredJsonMixin, View):
    """充值积分"""

    def get(self, request):
        """
                为了防止恶意访问，每次请求页面获取当前用户判断是否是管理员，
                如果是则访问，不是的话则直接跳出登录（给前端返回json，code==400，前端会去判断）
        :param request:
        :return:
        """

        user = request.user
        if user.is_superuser != 1:
            return JsonResponse({'code': 400})
        users = User.objects.filter(is_superuser=0)
        username = []
        for i in users:
            username.append({
                'username': i.username
            })
        return JsonResponse({"code": 200, "username": username})

    def post(self, request):
        user = request.user
        if user.is_superuser != 1:
            return JsonResponse({'code': 400})
        json_data = request.body.decode()
        json_dict = json.loads(json_data)
        name = json_dict.get("name")
        new_integral = json_dict.get("new_integral")
        kouling = json_dict.get("kouling")
        # print(kouling)
        user = authenticate(username=request.user.username, password=kouling)
        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '管理员密码错误,添加积分失败'})
        user = User.objects.filter(username=name).first()
        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '没有此的用户，不能将其添加积分'})
        userwallet = Userwallet.objects.filter(user=user).first()
        if userwallet is None:
            return JsonResponse({'code': 400, 'errmsg': '没有此用户的账户'})
        new_wallet = int(userwallet.wallet_income) + int(new_integral)
        userwallet.wallet_income = new_wallet
        userwallet.save()
        pay = AdminPay(user=user, integral=new_integral, admin_us=request.user.username)
        pay.save()
        return JsonResponse({'code': 0})


class Orders(LoginRequiredJsonMixin, View):
    """全部订单"""

    def get(self, request):
        """
        所有用户订单视图
        查询orderinfo
        根据orderinfo查询order-goods表，
        全部返回给前端
        """
        user = request.user
        if user.is_superuser != 1:
            return JsonResponse({'code': 400})
        oders = OrderInfo.objects.filter(total_count__gt=0, status=5).order_by('-create_time')
        oder_list = []
        for i in oders:
            tmp = {}
            tmp['order_id'] = i.order_id
            tmp['create_time'] = i.create_time.strftime("%Y-%m-%d- %H:%M:%S")
            # 'user':i.user.nick_name,
            tmp['total_count'] = i.total_count
            tmp['total_amount'] = i.total_amount
            tmp['status'] = i.user.username
            tmp['sku'] = []
            for j in i.skus.all():
                tmp['sku'].append({
                    'order': j.sku.name,
                    'price': j.price,
                    'count': j.count,
                    'img_url': str(j.sku.default_image.url)
                })
            oder_list.append(tmp)
        print(oder_list)
        return JsonResponse({'oder_list': oder_list})


class UserWallet(LoginRequiredJsonMixin, View):
    def get(self, request):
        user = request.user
        if user.is_superuser != 1:
            return JsonResponse({'code': 400})
        wallet_info = Userwallet.objects.all()
        data_wallet = []
        for i in wallet_info:
            data_wallet.append({
                "create_time": i.create_time.strftime("%Y-%m-%d- %H:%M:%S"),
                'wallet_income': i.wallet_income,
                "user": i.user.username,
            })
        return JsonResponse({"code": 200, "wallet_info": data_wallet})


class Allpys(LoginRequiredJsonMixin, View):

    def get(self, request):
        allapy = AdminPay.objects.all().order_by('-create_time')
        data = []
        for i in allapy:
            data.append({
                'user': i.user.username,
                'integral': i.integral,
                'admin_us': i.admin_us,
                'create_time': i.create_time.strftime("%Y-%m-%d- %H:%M:%S"),
            })

        return JsonResponse({'code': 200, 'data': data})
